package com.qf.login;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.qf.bo.LoginLogBO;
import com.qf.dao.LoginLogDao;
import com.qf.enums.ObjectFactory;
import com.qf.vo.ResultVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 认证成功
 *
 * @USER: Administrator
 * @DATE: 2025/8/31 上午12:02
 * @VERSION: 1.0.0
 */
@Component
public class LoginSuccessHandler implements AuthenticationSuccessHandler {

    /**
     * 未知的字符串常量，用于表示未知或未设置的值。
     */
    private static final String UNKNOWN = "unknown";

    @Autowired
    private LoginLogDao loginLogDao;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        // 设置响应类型为JSON格式，并设置字符集为UTF-8
        response.setContentType("application/json;charset=UTF-8");

        // 记录登录日志
        loginLogDao.insertLoginLog(LoginLogBO.LoginSuccess(authentication.getName(), request));

        // 返回数据给前端
        ObjectMapper objectMapper = ObjectFactory.INSTANCE.createInstance(ObjectMapper.class);
        response.getWriter().write(objectMapper.writeValueAsString(ResultVO.success()));

    }
}
